<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getQueryClues">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="impoortExcel">导入excel</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="dowloadExcel">导出excel</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handlDowloadExcelQuery">高级导出</el-button>
        </el-form-item>


      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="this.pageInfo.dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column prop="fullName" fixed label="客户名称">
      </el-table-column>
      <el-table-column prop="mphone" label="移动电话">
      </el-table-column>
<!--      <el-table-column prop="address" label="家庭地址" width="120" sortable>-->
<!--      </el-table-column>-->
      <el-table-column prop="source" label="来源">
      </el-table-column>
      <el-table-column prop="owner.username" label="销售人员">
      </el-table-column>

      <el-table-column prop="contactSummary" label="最近一次沟通记录">
      </el-table-column>
      <el-table-column prop="nextContactTime" label="下一次沟通">
      </el-table-column>

      <el-table-column prop="state" label="类型" >
        <template slot-scope="scope">
          <span v-if="scope.row.state==0" style="color: #18c79c">未分配</span>
          <span v-if="scope.row.state==1" style="color: #20a0ff">跟进中</span>
          <span v-if="scope.row.state==2" style="color: #dea726">已转商机</span>
          <span v-if="scope.row.state==-1" style="color: #5e7382">移入线索池</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="600">
        <template scope="scope">
          <el-button size="small"  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" v-if="scope.row.state==0" @click="handleAssign(scope.$index, scope.row)">分配</el-button>
          <el-button size="small" v-if="scope.row.state==1 || scope.row.state==2" @click="handleBusiness(scope.$index, scope.row)">转商机</el-button>
          <el-button size="small" v-if="scope.row.state==1 || scope.row.state==2" @click="handleEdit(scope.$index, scope.row)">跟进</el-button>
          <el-button size="small" v-if="scope.row.state==1 || scope.row.state==2" @click="handleAssign(scope.$index, scope.row)">移交</el-button>
          <el-button type="danger" v-if="scope.row.state==1" size="small" @click="handleDel(scope.$index, scope.row)">移入线索池</el-button>
          <el-button type="danger" v-if="scope.row.state==-1" size="small" @click="handleDel(scope.$index, scope.row)">尝试一下</el-button>
          <el-button type="danger" size="small" @click="handleActivitys(scope.$index, scope.row)">关联活动</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchAssign" :disabled="this.sels.length===0">批量分配</el-button>
      <!--	<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="this.query.pageSize" :total="this.pageInfo.total" style="float:right;">
        </el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="this.query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          style="float:right;"
          :total="this.pageInfo.total">
      </el-pagination>
    </el-col>
<!--//文件上传-->
    <el-dialog
        title="导入模板文件"
        :visible.sync="fileDialogVisible"
        width="50%"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        center
    >
      <el-upload
          ref="upload"
          class="upload-demo"
          action="#"
          accept=".xlsx, .xls"
          :auto-upload="false"
          :on-change="uploadFile"
          :show-file-list="false"
      >
        <el-button type="warning">导入线索</el-button>
      </el-upload>


    </el-dialog>

    <!--分配线索-->
    <el-dialog title="分配线索" :visible.sync="assignFormVisible" :close-on-click-modal="false">
      <el-form :model="assignForm" label-width="80px"  ref="addForm">
        <el-form-item label="线索信息" >
          <el-input   :disabled="true" v-model="assignForm.fullName" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="移动电话" >
          <el-input   :disabled="true" v-model="assignForm.mphone" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="固定电话" >
          <el-input   :disabled="true" v-model="assignForm.phone" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="销售人员" prop="owner">
          <el-select v-model="assignForm.owner" clearable value-key="id" placeholder="请选择">

            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="activityFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveAssign" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--批量分配-->
    <el-dialog title="批量分配" :visible.sync="batchAssignFormVisible" :close-on-click-modal="false">
      <el-form :model="batchAssignForm" label-width="80px"  ref="addForm">

        <el-form-item label="销售人员" prop="owner">
          <el-select v-model="batchAssignForm.owner" clearable value-key="id" placeholder="请选择">

            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="activityFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveBatchAssign" :loading="addLoading">提交</el-button>
      </div>

    </el-dialog>

    <!--转商机-->
    <el-dialog title="转商机" :visible.sync="businessFormVisible" :close-on-click-modal="false">
      <el-form :model="businessForm" label-width="80px"  ref="addForm">
        <el-form-item label="线索信息" >
          <el-input   :disabled="true" v-model="businessForm.fullName" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="移动电话" >
          <el-input   :disabled="true" v-model="businessForm.mphone" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="固定电话" >
          <el-input   :disabled="true" v-model="businessForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品" prop="product">
          <el-select v-model="businessForm.product" clearable value-key="id" placeholder="请选择">

            <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="activityFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveBusiness" :loading="addLoading">提交</el-button>
      </div>

    </el-dialog>
    <!--
      只有弹出模态框有这个问题 就是 v-model 绑定显示 不行 需要换成另一种写法 :visible.sync
      :rules="saveFormRules"  是规则
    -->
    <!--新增/修改界面-->
    <el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px"  ref="saveForm">
        <el-form-item label="客户名字" prop="fullName">
          <el-input v-model="saveForm.fullName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="客户昵称" prop="appellation">
          <el-input v-model="saveForm.appellation" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="客户电话" prop="mphone">
          <el-input v-model="saveForm.mphone" auto-complete="off"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--关联活动-->
    <el-dialog title="关联活动" :visible.sync="activityFormVisible" :close-on-click-modal="false">
      <el-form :model="activityFrom" label-width="80px"  ref="addForm">
        <el-form-item label="线索信息" >
          <el-input   :disabled="true" v-model="activityFrom.fullName" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="移动电话" >
          <el-input   :disabled="true" v-model="activityFrom.mphone" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="固定电话" >
          <el-input   :disabled="true" v-model="activityFrom.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="关联活动" v-model="activityFrom.activitys" label-width="80px" >

          <span v-for="(p,index) in Activitys" :key="p.id">
<!--<div class="checkbox-table" v-for="(p,indexkey) in permissionTree" :key="p.sn">-->
            <template>
              <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                           @change="activityChange(p.id)"
                           :label="p.id"
              >
                {{p.name}}
              </el-checkbox>

            </template>
          </span>
        </el-form-item>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="activityFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="addLoading">提交</el-button>
      </div>

    </el-dialog>

    <!--移交线索-->
<!--    <el-dialog title="分配线索" :visible.sync="assignFormVisible" :close-on-click-modal="false">-->
<!--      <el-form :model="assignForm" label-width="80px"  ref="addForm">-->
<!--        <el-form-item label="线索信息" >-->
<!--          <el-input   :disabled="true" v-model="assignForm.fullName" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="移动电话" >-->
<!--          <el-input   :disabled="true" v-model="assignForm.mphone" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="固定电话" >-->
<!--          <el-input   :disabled="true" v-model="assignForm.phone" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="销售人员" prop="owner">-->
<!--          <el-select v-model="assignForm.owner" clearable value-key="id" placeholder="请选择">-->

<!--            <el-option-->
<!--                v-for="item in employees"-->
<!--                :key="item.id"-->
<!--                :label="item.username"-->
<!--                :value="item">-->
<!--              <span style="float: left">{{ item.username }}</span>-->
<!--              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--      </el-form>-->

<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button @click.native="activityFormVisible = false">取消</el-button>-->
<!--        <el-button type="primary" @click.native="saveAssign" :loading="addLoading">提交</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'


export default {
  data() {
    return {

      //文件上传
      fileDialogVisible: false,
      //文件
      file: "",
      filename: "",
      filelist: [],
      errmesg: [],
      btn: {
        disable: false,
        message: "开始上传",
      },


      uploadVisible:false,

      // 商机--产品列表
      products:[],


    //显示转商机
      businessFormVisible:false,

      businessForm:{
        id:null,
        fullName:"",
        phone:"",
        mphone:"",
        product:{
          id:null,
          name:""
        }
      },


      batchAssignForm:{
        owner:{
          id:null,
          username:""
        },
        cluesId:[]
      },

      // 显示 批量分配
      batchAssignFormVisible:false,


      // 分配框显示
      assignFormVisible:false,

      //分配
      assignForm:{
        id:null,
        fullName:"",
        phone:"",
        mphone:"",
        owner:{
          id:null,
          username:""
        }
      },

      // 员工下拉框的数据
      employees:[],



      query: {
        keyword: '',
        currentPage:1,
        pageSize:10
      },
      pageInfo:{
        dataList: [],
        total: 0
      },
      page: 1,
      listLoading: false,
      sels: [],//列表选中列




      saveFormVisible: false,//新增界面是否显示
      addLoading: false,

      //新增界面数据
      saveForm: {
        id:null,
        fullName:"",
        appellation:"",
        mphone:"",
        description:"",
        activitys:[]

      },
      activityFormVisible:false,
      activityFrom:{
        id:null,
        fullName:"",
        appellation:"",
        mphone:"",
        description:"",
        activitys:[]
      },
      Activitys:[]

    }
  },
  methods: {

    handlDowloadExcelQuery(){
      this.query.currentPage = 1
      this.dowloadExcelQuery()
      // this.dowloadExcelQuery2()
    },

    dowloadExcelQuery2(){
      this.$http.post('/clue/dowmloadExcel/quey',this.query)
          .then(result=>{
            // result = result.data
            const blob = new Blob([result.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
            let link = document.createElement("a");
            let href = window.URL.createObjectURL(blob); //下载链接
            link.href = href;
            link.text = "下载";
            link.download = "高级查询下载"; //下载后文件名
            document.body.appendChild(link);
            link.click(); //点击下载
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(href);  //释放blob对象
          })
          .catch(result=>{
          })
    },



    dowloadExcelQuery(){
      this.$http({
        url: '/clue/dowmloadExcel/quey', //后端提供的接口
        method: 'post',
        responseType:'blob',
        data:this.query
      })
          .then(result=>{
            // result = result.data
            const blob = new Blob([result.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
            let link = document.createElement("a");
            let href = window.URL.createObjectURL(blob); //下载链接
            link.href = href;
            link.text = "下载";
            link.download = "高级查询下载"; //下载后文件名
            document.body.appendChild(link);
            link.click(); //点击下载
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(href);  //释放blob对象
          })
          .catch(result=>{
          })
    },

    dowloadExcel(){
      // this.$http.get("/cluedown/dowmloadExcel")

      this.$http({
        url: '/clue/dowmloadExcel', //后端提供的接口
        method: 'post',
        responseType:'blob',
      })
          .then(result=>{


            // result = result.data
              const blob = new Blob([result.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
              let link = document.createElement("a");
              let href = window.URL.createObjectURL(blob); //下载链接
              link.href = href;
              link.text = "下载";
              link.download = "aas"; //下载后文件名
              document.body.appendChild(link);
              link.click(); //点击下载
              document.body.removeChild(link); //下载完成移除元素
              window.URL.revokeObjectURL(href);  //释放blob对象


          })
          .catch(result=>{
          })
    },





    uploadFile (item) {
      let formData = new FormData()
      let file = item.raw
      formData.append('file', file)
      this.$http({
        url: '/clue/importExcel', //后端提供的接口
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(({data}) => {
        // this.$alert(data.data)
        this.fileDialogVisible=false
        this.getClues();
      })
    },



    // request({
    //           url: '/api/pu/unite/import/data',
    //           method: 'post',
    //           data: params,
    //           headers: { "Content-Type": "multipart/form-data" }
    //         });
    //上传文件
    //打开弹窗
    impoortExcel() {
      let that = this;
      that.fileDialogVisible= true;
    },

//关闭弹窗 移除数据
    handleDialogClose() {
      this.filelist = [];
      this.file = "";
      this.fileDialogVisible = false;
    },

    //保存转商机信息
    saveBusiness(){
      this.$http.post("/clue/transferBusiness",this.businessForm)
          .then(result=>{
            result = result.data
            if (result.success){
              this.businessFormVisible = false
            }else{
            }
          })
          .catch(result=>{
          })
    },

    handleBusiness(index,row){
      this.businessFormVisible=true
      this.businessForm=row
      this.getProducts()
    },

  // 获取产品列表
    getProducts() {
      this.$http.get("/product")
          .then(result=>{
            result = result.data
            if (result.success){

              this.products = result.resultObj
            }else{

            }
          })
          .catch(result=>{

          })
    },

    // 保存批量分配
    saveBatchAssign(){

      console.log(this.batchAssignForm);
      this.$http.post("/clue/batchAssign",this.batchAssignForm)
          .then(result=>{
            result = result.data
            if (result.success){
              this.batchAssignFormVisible = false
              this.$message({message: '保存成功', type: 'success' });
              this.getClues()

            }else{
            }
          })
          .catch(result=>{
            // 这里的catch是发请求都出了问题

          })
    },


    //显示批量分配
    batchAssign(){
      this.batchAssignFormVisible=true
      this.getEmployees();
    },




    //保存、提交 分配
    saveAssign(){
      this.$http.post("/clue/assign",this.assignForm)
          .then(result=>{
            result = result.data
            if (result.success){
              this.assignFormVisible = false
              this.$message({message: '保存成功', type: 'success' });
              this.getClues()
            }else{

            }
          })
          .catch(result=>{
            // 这里的catch是发请求都出了问题

          })
    },

    //显示分配界面方法
    handleAssign(index,row){
      console.log(row);
      this.assignFormVisible = true
      this.assignForm = row;
      this.getEmployees()
    },

    //获取员工列表
    getEmployees() {

      this.$http.get("/employee")
          .then(result=>{
            result = result.data
            if (result.success){
              this.$message({message: '查询成功', type: 'success' });
              this.listLoading = false;
              this.employees = result.resultObj
            }else{
              this.$message({message: '查询失败', type: 'danger' });
            }
          })
          .catch(result=>{

          })

    },



    // 保存关联活动的方法
    saveSubmit(){
      this.$http.post("/activity/clue",this.activityFrom)
          .then(result=>{
            result = result.data
            if (result.success){
              this.$message({message: '保存成功', type: 'success' });
              this.activityFormVisible = false;
            }else{

            }
          })
          .catch(result=>{

          })
    },
    activityChange(id){

      var number = this.activityFrom.activitys.indexOf(id);
      // number 如果大于 -1 说明存在 如果小于等于-1 说明 不存在
      if (number > -1){
        this.activityFrom.activitys.splice(number,1)
      }else{
        this.activityFrom.activitys.push(id);
      }
      console.log(this.activityFrom.activitys)
    },
    // 关联活动
    handleActivitys(index,row){
      this.activityFormVisible = true
      this.activityFrom = row
      if (!this.activityFrom.activitys){
        this.activityFrom.activitys = []
      }
      this.getBindActivitys(row.id); // 查询已经关联的活动
      this.getActivitys(); // 查询所有的关联活动
    },
    getBindActivitys(id){
      this.$http.get("/clue/activity/"+id)
          .then(result=>{
            result = result.data
            if (result.success){
              debugger
              this.activityFrom.activitys = result.resultObj;
              console.log(this.activityFrom.activitys);
            }else{

            }
          })
          .catch(result=>{

          })
    },
    // 获取活动的方法
    getActivitys(){
      this.$http.get("/activity")
          .then(result=>{
            result = result.data
            if (result.success){
              this.Activitys = result.resultObj;
            }else{

            }
          })
          .catch(result=>{

          })
    },

    handleSizeChange(val){
      this.query.pageSize = val;
      this.getClues()
    },
    // 点击查询按钮
    getQueryClues(){
      this.query.currentPage = 1
      this.getClues()
    },

    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getClues()
    },
    //获取部门列表
    getClues() {
      // No 'Access-Control-Allow-Origin'
      // 只要看到浏览器报这个错误就是跨域问题 前后端分离的项目一定会有跨越问题
      this.listLoading = true;
      // 发请求
      // localhost:8080/clue  全局的前缀

      this.$http.put("/clue",this.query)
          .then(result=>{
            result = result.data
            if (result.success){
              this.$message({message: '查询成功', type: 'success' });
              this.listLoading = false;
              this.pageInfo = result.resultObj
              console.log(this.pageInfo.dataList);
            }else{

            }
          })
          .catch(result=>{

          })

    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; // 模态框
        //NProgress.start();
        let para = { id: row.id };
        //发请求
        this.$http.delete("/clue/"+row.id)
            .then(result=>{
              result = result.data
              if (result.success){
                this.$message({message: '删除成功', type: 'success' });
                this.listLoading = false;
                this.query.currentPage = 1;
                // 刷新列表
                this.getClues()
              }else{
                this.$message({message: '删除失败', type: 'danger' });
              }
            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);// 将行数据  赋值给  saveForm

    },
    //显示移交界面
    handleTransfer(){

    },

    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id:null,
        fullName:"",
        appellation:"",
        mphone:"",
        description:"",
        clue:[]
      }

    },

    handleUpload(){
      this.uploadVisible=true
    },


    //新增
    addSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            let para = Object.assign({}, this.saveForm); // json格式的转换
            // 处理父级级联框
            // 发请求
            this.$http.post("/clue",para)
                .then(result=>{
                  result = result.data
                  if (result.success){
                    this.$message({message: '保存成功', type: 'success' });
                    this.addLoading = false;
                    this.saveFormVisible = false
                    // 刷新列表
                    this.getClues()
                  }else{
                    this.$message({message: '保存失败', type: 'danger' });
                  }
                })
                .catch(result=>{
                  // 这里的catch是发请求都出了问题
                  this.$message({message: '网络异常,请检查您的网络', type: 'danger' });
                })
          }).catch({})


        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
      var ids = sels.map(x=>x.id);
      this.batchAssignForm.cluesId = ids;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 发请求
        this.$http.patch("/clue",ids)
            .then(result=>{
              result = result.data
              if (result.success){
                this.$message({message: '批量删除成功', type: 'success' });
                this.listLoading = false;
                this.query.currentPage = 1;
                // 刷新列表
                this.getClues()
              }else{
                this.$message({message: '批量删除失败', type: 'danger' });
              }
            })
            .catch(result=>{

            })
      })
          .catch(() => {

          });
    }
  },
  mounted() {
    this.getClues();
  }
}

</script>

<style scoped>

</style>